package com.bankcomm.creditcard.redfriday.shop;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.ProgressDialog;
import android.content.Intent;
import android.location.Location;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.Spinner;
import android.widget.TextView;

import com.bankcomm.creditcard.redfriday.BaseActivity;
import com.bankcomm.creditcard.redfriday.MainActivity;
import com.bankcomm.creditcard.redfriday.R;
import com.bankcomm.creditcard.redfriday.data.GPS;
import com.bankcomm.creditcard.redfriday.data.Shop;
import com.bankcomm.creditcard.redfriday.map.baidu.BaiduMapActivity;

public class ShopListActivity extends BaseActivity {
	private static final String TAG = "ShopListActivity";
	private ShopListAdapter mAdapter = null;
	private List<Shop> mList = new ArrayList<Shop>();
	private ProgressDialog mProgressDialog;
	private TextView mNoListViewTextView;
	private int mMapDistance = 1;
	private int mShopNum = 20;
	private Map<String, String> mRequestParameter = new HashMap<String, String>();
	// private boolean mIsMore = false;
	private int mCurPage = 0;
	private ListView mListView;

	// private Button mMoreBtn;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.shoplist);
		int index = getIntent().getIntExtra("index",
				BaseActivity.INDEX_SUPERMARKET);
		String[] shopArray = getResources().getStringArray(R.array.shop_array);

		TextView titleTextView = (TextView) findViewById(R.id.header_title);
		titleTextView.setText(R.string.shop);
		Button backBtn = (Button) findViewById(R.id.header_back);
		backBtn.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				finish();
			}
		});

		Button homeBtn = (Button) findViewById(R.id.header_home);
		homeBtn.setVisibility(View.VISIBLE);
		homeBtn.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				Intent intent = new Intent(getApplicationContext(),
						MainActivity.class);
				intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
				startActivity(intent);
			}
		});

		mProgressDialog = new ProgressDialog(this);
		mProgressDialog.setMessage(getString(R.string.progressdialog_message));
		mProgressDialog.setCancelable(false);
		mNoListViewTextView = (TextView) findViewById(R.id.shoplist_nolistview);

		TextView shopTextView = (TextView) findViewById(R.id.shoplist_shop);
		shopTextView.setText(shopArray[index]);

		mListView = (ListView) findViewById(R.id.shoplist_listview);
		// mMoreBtn = new Button(getApplicationContext());
		// mMoreBtn.setGravity(Gravity.CENTER);
		// mMoreBtn.setVisibility(View.GONE);
		// mMoreBtn.setBackgroundResource(R.drawable.button);
		// mMoreBtn.setOnClickListener(new OnClickListener() {

		// @Override
		// public void onClick(View v) {
		// // TODO Auto-generated method stub
		// mCurPage++;
		// mRequestParameter.put("curpage", mCurPage + "");
		// mIsMore = true;
		// mProgressDialog.show();
		// startRequest(BaseActivity.METHOD_GETBYGPS, mRequestParameter);
		// }
		// });
		// mListView.addFooterView(mMoreBtn);

		mAdapter = new ShopListAdapter(getApplicationContext(), mList);
		mListView.setAdapter(mAdapter);

		final int tmpIndex = index;
		mListView.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				// TODO Auto-generated method stub
				Intent intent = new Intent(getApplicationContext(),
						ShopActivity.class);
				intent.putExtra("index", tmpIndex);
				intent.putExtra("shop", mList.get(position));
				startActivity(intent);
			}
		});

		mRequestParameter.put("lng", String.valueOf(GPS.LNG));
		mRequestParameter.put("lat", String.valueOf(GPS.LAT));
		mRequestParameter.put("distance", mMapDistance + "");
		switch (index) {
		case BaseActivity.INDEX_SUPERMARKET:
			mRequestParameter.put("type", "3");
			break;
		case BaseActivity.INDEX_GASSTATION:
			mRequestParameter.put("type", "1");
			break;
		case BaseActivity.INDEX_FIFTY:
			mRequestParameter.put("type", "2");
			break;
		default:
			mRequestParameter.put("type", "3");
			break;
		}

		mRequestParameter.put("count", mShopNum + "");

		// mProgressDialog.show();
		// startRequest(BaseActivity.METHOD_GETBYGPS, requestParameter);

		Spinner spinner = (Spinner) findViewById(R.id.shoplist_map_distance_spinner);
		ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(
				this, R.array.map_distance_array,
				android.R.layout.simple_spinner_item);
		adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		spinner.setAdapter(adapter);
		final int finalIndex = index;
		spinner.setOnItemSelectedListener(new OnItemSelectedListener() {

			@Override
			public void onItemSelected(AdapterView<?> parent, View view,
					int position, long id) {
				// TODO Auto-generated method stub
				switch (position) {
				case 0:// 1公里以内
					mMapDistance = 1;
					break;
				case 1:// 3公里以内
					mMapDistance = 3;
					break;
				case 2:// 5公里以内
					mMapDistance = 5;
					break;
				case 3:// 10公里以内
					mMapDistance = 10;
					break;
				case 4:// 显示全部
					mMapDistance = 0;
					break;
				default:
					mMapDistance = 1;
					break;
				}
				if (mMapDistance == 0) {
					String url = "";
					if (finalIndex == BaseActivity.INDEX_SUPERMARKET
							|| finalIndex == BaseActivity.INDEX_GASSTATION) {
						url = "http://creditcardbeta.bankcomm.com/benefit/RedFriday.aspx";
					} else {
						url = "http://creditcardbeta.bankcomm.com/benefit/C50B50.aspx";
					}
					Intent intent = new Intent(Intent.ACTION_VIEW, Uri
							.parse(url));
					startActivity(intent);
				} else {
					mCurPage = 0;
					mRequestParameter.put("curpage", mCurPage + "");
					mRequestParameter.put("distance", mMapDistance + "");
					mProgressDialog.show();
					// mIsMore = false;
					startRequest(BaseActivity.METHOD_GETBYGPS,
							mRequestParameter);
				}
			}

			@Override
			public void onNothingSelected(AdapterView<?> parent) {
				// TODO Auto-generated method stub

			}
		});

		Button mapBtn = (Button) findViewById(R.id.shoplist_map_btn);
		mapBtn.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				Intent intent = new Intent(getApplicationContext(),
						BaiduMapActivity.class);
				ArrayList<Bundle> list = new ArrayList<Bundle>();
				Bundle bundle = null;
				for (Iterator<Shop> iterator = mList.iterator(); iterator
						.hasNext();) {
					bundle = new Bundle();
					Shop shop = iterator.next();
					bundle.putSerializable("shop", shop);
					list.add(bundle);
				}
				intent.putParcelableArrayListExtra("shops", list);
				intent.putExtra("from", "shoplist");
				startActivity(intent);
			}
		});

	}

	@Override
	protected void parseJson(String jsonString) {
		// TODO Auto-generated method stub
		try {
			JSONArray jsonArray = new JSONArray(jsonString);
			if (jsonArray != null && jsonArray.length() > 0) {
				// if (!mIsMore) {
				mList.clear();
				// }
				JSONObject jsonObject = null;
				Shop shop = null;
				for (int i = 0; i < jsonArray.length(); i++) {
					shop = new Shop();
					jsonObject = (JSONObject) jsonArray.get(i);
					if (jsonObject.has("id")) {
						shop.id = jsonObject.getString("id");
					}
					if (jsonObject.has("province")) {
						shop.province = jsonObject.getString("province");
					}
					if (jsonObject.has("city")) {
						shop.city = jsonObject.getString("city");
					}
					if (jsonObject.has("marketTitle")) {
						shop.marketTitle = jsonObject.getString("marketTitle");
					}
					if (jsonObject.has("address")) {
						shop.address = jsonObject.getString("address");
					}
					if (jsonObject.has("startTime")) {
						shop.startTime = jsonObject.getString("startTime");
					}
					if (jsonObject.has("endTime")) {
						shop.endTime = jsonObject.getString("endTime");
					}
					if (jsonObject.has("lng")) {
						shop.lng = jsonObject.getDouble("lng");
					}
					if (jsonObject.has("lat")) {
						shop.lat = jsonObject.getDouble("lat");
					}
					if (jsonObject.has("shopType")) {
						shop.shopType = jsonObject.getString("shopType");
					}
					float[] results = new float[3];
					Location.distanceBetween(GPS.LAT, GPS.LNG, shop.lat,
							shop.lng, results);
					if (results.length > 1) {
						shop.distance = results[0];
					}
					mList.add(shop);
					Collections.sort(mList, new Comparator<Shop>() {

						@Override
						public int compare(Shop lhs, Shop rhs) {
							// TODO Auto-generated method stub
							if (lhs.distance < rhs.distance) {
								return -1;
							} else if (lhs.distance == rhs.distance) {
								return 0;
							} else if (lhs.distance > rhs.distance) {
								return 1;
							}
							return 1;
						}
					});
				}
			}
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			Log.e(TAG, "parseJson: " + e.toString());
		}

	}

	@Override
	protected void refreshView() {
		// TODO Auto-generated method stub
		mProgressDialog.dismiss();
		if (mList == null || mList.isEmpty()) {
			mNoListViewTextView.setVisibility(View.VISIBLE);
			// mMoreBtn.setVisibility(View.GONE);
		} else {
			mNoListViewTextView.setVisibility(View.GONE);
			// mMoreBtn.setVisibility(View.VISIBLE);
		}
		mAdapter.notifyDataSetChanged();
		// mListView.setSelection(mList.size());
	}

}
